package com.mt.api.modules.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.mt.api.modules.domain.dto.OrderStatByCargoDto;
import com.mt.common.response.WebResponse;
import com.mt.common.response.WebResponseUtils;
import com.mt.api.modules.domain.bo.AppReportCargoNoBo;
import com.mt.api.modules.mapper.AppReportMapper;
import com.mt.api.modules.service.AppReportService;
import lombok.RequiredArgsConstructor;
import com.mt.common.utils.PloverDateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author: plover
 * @Date: 2020/07/15/3:36 下午
 * @Description:
 */
@Service
@RequiredArgsConstructor
public class AppReportServiceImpl implements AppReportService {


    private final AppReportMapper appReportMapper;

    /**
     * https://echarts.apache.org/examples/zh/editor.html?c=dataset-simple1
     * option = {
     * legend: {},
     * tooltip: {},
     * dataset: {
     * dimensions: ['product', '2015', '2016', '2017'],
     * source: [
     * {product: 'Matcha Latte', '2015': 43.3, '2016': 85.8, '2017': 93.7},
     * {product: 'Milk Tea', '2015': 83.1, '2016': 73.4, '2017': 55.1},
     * {product: 'Cheese Cocoa', '2015': 86.4, '2016': 65.2, '2017': 82.5},
     * {product: 'Walnut Brownie', '2015': 72.4, '2016': 53.9, '2017': 39.1}
     * ]
     * },
     * xAxis: {type: 'category'},
     * yAxis: {},
     * // Declare several bar series, each will be mapped
     * // to a column of dataset.source by default.
     * series: [
     * {type: 'bar'},
     * {type: 'bar'},
     * {type: 'bar'}
     * ]
     * };
     *
     * @param reportCargoNoBo
     * @return
     */
    @Override
    public WebResponse getSalesByCargoNoPerDay(AppReportCargoNoBo reportCargoNoBo) {
        LocalDate localDateTime = LocalDate.now().plusDays(0 - reportCargoNoBo.getDays());
        Date startDate = PloverDateUtil.toDate(localDateTime);
        List<OrderStatByCargoDto> records = appReportMapper.queryByDayAndCargoNo(startDate);

        JSONObject result = new JSONObject();
        JSONObject dataset = new JSONObject();
        List<String> dimensions = Lists.newArrayList();
        List<JSONObject> source = Lists.newArrayList();
        dimensions.add("product");

        List<String> orderDates = records.stream().map(orderStatByCargoDto -> PloverDateUtil.dateToMMdd(orderStatByCargoDto.getOrderDate())).distinct().collect(Collectors.toList());

        List<String> cargoNos = records.stream().map(OrderStatByCargoDto::getCargoNo).sorted(String::compareTo).distinct().collect(Collectors.toList());
        dimensions.addAll(cargoNos);

        orderDates.forEach(orderDate -> {
            JSONObject productObj = new JSONObject();
            dimensions.forEach(cargoNo -> {
                if (!StringUtils.equals("product", cargoNo)) {
                    Optional<Integer> dataOptional = records.stream().filter(orderStatByCargoDto -> StringUtils.equals(orderStatByCargoDto.getCargoNo(), cargoNo)
                            && StringUtils.equals(PloverDateUtil.dateToMMdd(orderStatByCargoDto.getOrderDate()), orderDate))
                            .map(OrderStatByCargoDto::getQty).findFirst();
                    if (dataOptional.isPresent()) {
                        productObj.put(cargoNo, dataOptional.get());
                    }
                }
            });
            productObj.put("product", orderDate);
            source.add(productObj);
        });
        dataset.put("dimensions", dimensions);
        dataset.put("source", source);
        result.put("dataset", dataset);
        return WebResponseUtils.success(result);
    }

    /**
     * https://echarts.apache.org/examples/zh/editor.html?c=line-smooth
     * option = {
     * xAxis: {
     * type: 'category',
     * data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
     * },
     * yAxis: {
     * type: 'value'
     * },
     * series: [{
     * data: [820, 932, 901, 934, 1290, 1330, 1320],
     * type: 'line',
     * smooth: true
     * }]
     * };
     *
     * @return
     */
    @Override
    public WebResponse getSalesPerDay(AppReportCargoNoBo reportCargoNoBo) {
        LocalDateTime localDateTime = LocalDateTime.now().plusDays(0 - reportCargoNoBo.getDays());
        String beginDate = PloverDateUtil.localDateTimeFormatyMd(localDateTime);

        List<JSONObject> dataList = appReportMapper.queryByDay(beginDate);
        List<String> xAxisData = Lists.newArrayList();
        List<Integer> seriesData = Lists.newArrayList();
        dataList.forEach(jsonObject -> {
            xAxisData.add(PloverDateUtil.dateToMMdd(jsonObject.getString("order_date")));
            seriesData.add(jsonObject.getIntValue("total_qty"));
        });
        JSONObject result = new JSONObject();
        result.put("xAxisData", xAxisData);
        result.put("seriesData", seriesData);
        return WebResponseUtils.success(result);
    }

}

